package com.example.idie.service;

import cn.hutool.core.io.FileUtil;
import com.example.idie.bean.Response;
import com.example.idie.bean.SSHServiceBean;
import com.example.idie.util.FtpUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.Map;

@Service
public class SSHServiceImpl implements SSHService{


    @Override
    public Response<String> uploadSingleFile(MultipartFile file) throws Exception {
        String newFileName = "TEMP_IMG.jpg";
        byte[] bytes = file.getBytes();
        FtpUtil ftpUtil = new FtpUtil();
        ftpUtil.sshPrivateKeySave(bytes, newFileName);
        System.out.println("上传成功:" + newFileName);

        return Response.success("success");
    }

    @Override
    public Response<String> download(String filename, HttpServletResponse response) throws Exception {
        FtpUtil ftpUtil = new FtpUtil();
        if (filename.equals("TEMP_RESULT.jpg")) {

            File resImage = ftpUtil.sshPrivateKeyRead("TEMP_RESULT.jpg");
            String filePath = resImage.getPath();

            if (!FileUtil.exist(filePath)) {
                return Response.fail(1000, "没有结果图片！");
            }
            byte[] bytes = FileUtil.readBytes(filePath);
            response.setContentType("image/png");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();

            return Response.success("推理成功！");

        } else if (filename.equals("TEMP.json")) {
            File file = ftpUtil.sshPrivateKeyRead(filename);
            String json = "";
            if (file != null) {
                json = new String(Files.readAllBytes(file.toPath()));
                System.out.println(json);
            }
            return Response.success(json);

        } else if (filename.equals("TEMP_LOG.log")) {
            String command = "cd /data2/suyou/Codes/medicine/results && sed -r \"s/\\x1B\\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g\" temp.log > TEMP_LOG.log";
            String host = "amax6.xjtu.io";
            String username = "suyou";
            String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
            int port = 47982;

            SSHServiceBean sshService = new SSHServiceBean(host, port, username, privateKeyPath);
            sshService.executeCommand(command);

            File file = ftpUtil.sshPrivateKeyRead(filename);
            String log = "";
            if (file != null) {
                log = new String(Files.readAllBytes(file.toPath()));
                System.out.println(log);
            }
            return Response.success(log);

        } else {
            return Response.fail(1000, "无该文件！");
        }
    }

    @Override
    public Response<String> infer(MultipartFile file) throws Exception {
        // 1. 上传一张图片JPG格式，保存到指定目录 /data2/suyou/Codes/medicine/results/TEMP_IMG.jpg
        Response<String> uploadRes = uploadSingleFile(file);

        if (uploadRes.getCode() != 1000) {
            return uploadRes;
        }

        // 2. 执行命令进行推理 python visualization_infer.py
        String command = "cd /data2/suyou/Codes/medicine/ && /data2/suyou/anaconda/myconda/envs/paddle/bin/python /data2/suyou/Codes/medicine/visualization_infer.py";
        String host = "amax6.xjtu.io";
        String username = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;

        SSHServiceBean sshService = new SSHServiceBean(host, port, username, privateKeyPath);
        sshService.executeCommand(command);

        return Response.success("推理成功！");
    }

    @Override
    public Response<String> train(Map<String, String> hyperParameters) throws Exception {
        String lr = hyperParameters.get("lr");
        String epoch = hyperParameters.get("epoch");
        String command = "cd /data2/suyou/Codes/medicine/ && bash finetune.sh " + lr + " " + epoch + " 2>&1 | tee ./results/temp.log";
        String host = "amax6.xjtu.io";
        String username = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;

        SSHServiceBean sshService = new SSHServiceBean(host, port, username, privateKeyPath);
        sshService.executeCommandThread(command);

        return Response.success("开始训练！");
    }
}
